import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import Cookie from 'js-cookie'
import NProgress from 'nprogress'
import asyncRouter from './asyncRouter'
import whiteList from './whiteList'

// 页面刷新重新赋值token
if (Cookie.get('token')) {
  store.dispatch('relogin')
}

NProgress.configure({
  showSpinner: false
})

Vue.use(VueRouter)

/**
 * 根据权限匹配路由
 * @param {array} permission 权限列表（菜单列表）
 * @param {array} asyncRouter 异步路由对象
 */
function routerMatch (permission, asyncRouter) {
  return new Promise(resolve => {
    const routers = asyncRouter[0]
    // 创建路由
    function createRouter (permission) {
      permission.forEach(item => {
        if (item.child && item.child.length) {
          // 递归
          createRouter(item.child)
        }
        let path = item.path
        // 循环异步路由，将符合权限列表的路由加入routers中
        asyncRouter.find(function (s) {
          if (s.path === path) {
            s.meta.permission = item.permission
            routers.children.push(s)
          }
        })
      })
    }

    createRouter(permission)
    resolve([routers])
  })
}

// 默认路由表，不需要权限
const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    component: () => import('../views/login/login')
  },
  {
    path: '/defaultLayout',
    component: () => import('../views/layout/layout'),
    meta: {
      permission: []
    },
    // 需要进行用户登录验证
    children: [
      {
        path: '/home',
        component: () => import('../views/home/home')
      }
    ]
  },
  {
    path: '/error',
    component: () => import('../views/error/error')
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 路由跳转前验证
router.beforeEach((to, from, next) => {
  // 开启进度条
  NProgress.start()
  // 判断用户是否登录
  if (Cookie.get('token')) {
    // 判断是否存在权限列表
    let list = store.state.permission
    if (!list.length) {
      store.dispatch('getPermission').then(res => {
        // 匹配并生成需要添加的路由对象
        routerMatch(res.data, asyncRouter).then(res => {
          router.addRoutes(res)
          next(to.fullPath)
        })
      }).catch(() => {
        store.dispatch('logout').then(() => {
          router.replace('/login')
        })
      })
    } else {
      // 如果跳转页面存在于路由中则进入，否则跳转到404
      // 因为可以通过改变url值进行访问，所以必须有该判断
      if (to.matched.length) {
        if (whiteList.indexOf(to.path) < 0) {
        }
        next()
      } else {
        router.replace('/error/404')
      }
    }
  } else {
    // 如果是免登陆的页面则直接进入，否则跳转到登录页面
    if (whiteList.indexOf(to.path) >= 0) {
      next()
    } else {
      router.replace('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})

export default router
